package com.atguigu.lease.web.app.controller.room;


import com.atguigu.lease.common.result.Result;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.BrowsingHistory;
import com.atguigu.lease.web.app.service.BrowsingHistoryService;
import com.atguigu.lease.web.app.service.RoomInfoService;
import com.atguigu.lease.web.app.vo.room.RoomDetailVo;
import com.atguigu.lease.web.app.vo.room.RoomItemVo;
import com.atguigu.lease.web.app.vo.room.RoomQueryVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.jsonwebtoken.Claims;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@Tag(name = "房间信息")
@RestController
@RequestMapping("/app/room")
public class RoomController {
@Autowired
private RoomInfoService roomInfoService;
@Autowired
private BrowsingHistoryService browsingHistoryService;
    @Operation(summary = "分页查询房间列表")
    @GetMapping("pageItem")
    public Result<IPage<RoomItemVo>> pageItem(@RequestParam long current, @RequestParam long size, RoomQueryVo queryVo) {
        Page<RoomItemVo> page = new Page<>(current,size);
        roomInfoService.customPage(page,queryVo);
        return Result.ok(page);
    }

    @Operation(summary = "根据id获取房间的详细信息")
    @GetMapping("getDetailById")
    public Result<RoomDetailVo> getDetailById(@RequestParam Long id, @RequestHeader("access_token") String token) {
        RoomDetailVo roomDetailVo = roomInfoService.customGetDetailById(id);
        Long userId = JwtUtil.parseToken(token).get("userId", Long.class);
    /*   新增浏览历史功能逻辑:因为拦截器把除了登录界面的以外的资源都拦截了,所以只要能进来,就代表用户一定登录了,
        一定有一个token,而用户进来的时候只要点击一个房间(对应的就是当前接口),就会产生一条记录,通过每次
        通过房间id查询房间详细信息,每次都会在浏览历史记录里保存一条新的记录,又因为浏览记录是在某一瞬间产生的,
        所以浏览历史记录里对应的每一条记录都是独立的记录, BrowseTime,CreateTime,UpdateTime都是一样的时间.
        而在前端页面显示历史记录的时候,应该是从最新的访问时间开始显示,所以查询浏览记录应该降序排列
    */
        BrowsingHistory browsingHistory = new BrowsingHistory();
        browsingHistory.setUserId(userId);
        browsingHistory.setBrowseTime(new Date());
        browsingHistory.setCreateTime(new Date());
        browsingHistory.setUpdateTime(new Date());
        browsingHistory.setIsDeleted((byte)0);
        browsingHistory.setRoomId(roomDetailVo.getId());
        browsingHistoryService.save(browsingHistory);
        return Result.ok(roomDetailVo);
    }

    @Operation(summary = "根据公寓id分页查询房间列表")
    @GetMapping("pageItemByApartmentId")
    public Result<IPage<RoomItemVo>> pageItemByApartmentId(@RequestParam long current, @RequestParam long size, @RequestParam Long id) {
        Page<RoomItemVo> page = new Page<>(current,size);
        roomInfoService.customPageByapartId(page,id);
        return Result.ok(page);
    }
}
